import 'dart:convert';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_easyrefresh/material_footer.dart';
import 'package:flutter_easyrefresh/material_header.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:panda/base/SignType.dart';
import 'package:panda/entity/article_list_entity.dart';
import 'package:panda/http/Api.dart';
import 'package:panda/http/HttpUtil.dart';
import 'package:panda/util/PreviewImagesWidget.dart';
import 'package:panda/util/SignUtil.dart';

import '../base/Constant.dart';

class PlayBillChildPage extends StatefulWidget {
  String id;
  PlayBillChildPage({Key key, @required this.id}) : super(key: key);

  @override
  _PlayBillChildPageState createState() => _PlayBillChildPageState();
}

class _PlayBillChildPageState extends State<PlayBillChildPage>
    with AutomaticKeepAliveClientMixin {
  EasyRefreshController _controller = new EasyRefreshController();
  List<HomeListDataData> dataList = new List();

  int page = 1;
  @override
  void initState() {
    super.initState();
    loadList();
  }

  loadList() async {
    Map map = new Map();
    map['cat_id'] = widget.id;
    map['p'] = page.toString();
    map['per'] = "10";
    map['sign_type'] = SignType.GET_ARTICLE_LIST;
    Response<String> response =
        await HttpUtil().post(Api.GET_SYSTEM_ARTICLE, data: getSign(map));
    print(response.data);
    Map userMap = json.decode(response.data);
    HomeListEntity homeServiceEntity = new HomeListEntity.fromJson(userMap);
    if (userMap['code'] == 1 && mounted) {
      if (page == 1) {
        dataList.clear();
        _controller.resetLoadState();
        _controller.finishRefresh();
      } else {
        _controller.finishLoad(
            noMore: homeServiceEntity.data.datas.length == 0);
        if (homeServiceEntity.data.datas.length == 0) {
          Fluttertoast.showToast(msg: "已经加载全部");
        }
      }
      dataList.addAll(homeServiceEntity.data.datas);
      setState(() {});
    }
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return new EasyRefresh(
      controller: _controller,
      header: MaterialHeader(),
      footer: MaterialFooter(),
      enableControlFinishLoad: true,
      enableControlFinishRefresh: true,
      onLoad: () {
        page++;
        loadList();
      },
      onRefresh: () {
        page = 1;
        loadList();
      },
      child: Container(
        padding: EdgeInsets.all(
          ScreenUtil.getInstance().setHeight(DP_20),
        ),
        child: GridView.builder(
          shrinkWrap: true,
          padding: EdgeInsets.only(top: 0),
          physics: new NeverScrollableScrollPhysics(),
          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: 3,
              mainAxisSpacing: ScreenUtil.getInstance().setHeight(DP_15),
              crossAxisSpacing: ScreenUtil.getInstance().setHeight(DP_15),
              childAspectRatio: 0.6),
          itemBuilder: (BuildContext context, int index) {
            return GestureDetector(
              child: renderRow(context, index),
              onTap: () {
                List<String> imgs = new List();
                for (int i = 0; i < dataList.length; i++) {
                  imgs.add(Api.ImgBaseUrl + dataList[i].img);
                }
                Navigator.of(context).push(PageRouteBuilder(
                    pageBuilder: (c, a, s) => PreviewImagesWidget(
                          imgs,
                          initialPage: index,
                        )));
              },
            );
          },
          itemCount: dataList.length,
        ),
      ),
    );
  }

  Widget renderRow(BuildContext context, int index) {
    return CachedNetworkImage(
                imageUrl:
      Api.ImgBaseUrl + dataList[index].img,
      width: (MediaQuery.of(context).size.width -
              ScreenUtil.getInstance().setHeight(DP_80 - 10)) /
          3,
      fit: BoxFit.fill,
      height: 10 *
          (MediaQuery.of(context).size.width -
              ScreenUtil.getInstance().setHeight(DP_80 - 10)) /
          3 /
          6,
    );
  }

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;
}
